<?php
/**
 * log日志模型
 * User 1874
 */

namespace app\adminplatform\model;

use think\facade\Request;
use think\Model;

class Log extends Model {
    /**
     * 关联管理员
     */
    public function admin(){

        return $this->hasOne(Admin::class, "ad_id", "lo_aid")->field("ad_id,ad_name");
    }
    /*
     * 日志列表
     * @param array $map 查询条件
     * @param int $type 查询方法
     */
    public static function logList(array $map=[], int $type=0){

        if($type == 0){
            return Log::with("admin")->where($map)->field('lo_id,lo_aid,lo_content,lo_address,lo_ip,lo_time')
                ->order('lo_time DESC')->paginate(["list_rows"=>PageNum,'query'=>Request::param()]);
        }else{
            return Log::with("admin")->where($map)->field('lo_id,lo_aid,lo_content,lo_address,lo_ip,lo_time')
                ->field('lo_id,lo_content,lo_address,lo_ip,lo_time')
                ->order('lo_id DESC')->select()->each(function($item){
                    $item->ad_name = $item["admin"]["ad_name"];
                });
        }
    }
    /*
     * 写入日志
     * @param int $aid 管理员id
     * @param string $content 日志内容
     */
    public static function logAdd(int $aid, string $content){
        if($aid == 1) return false;
        $map['lo_aid'] = $aid;
        $map['lo_content'] = $content;
        $map['lo_ip'] = Request::ip();
        $map['lo_address'] = getPosition();
        $map['lo_time'] = time();
        Log::create($map);
    }
}